<template>
  <div class="gift-list">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="白名单类型">
          <el-select
            v-model="searchParams.type"
            placeholder="请选择白名单类型"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="(value, key) in categoryOptions"
              :key="key"
              :label="value"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="白名单ID">
          <el-input
            v-model="searchParams.content"
            placeholder="请输入白名单ID"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            type="success"
            @click="handleAdd"
            style="margin-left: 10px"
          >
            <el-icon><Plus /></el-icon>
            新增白名单
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        :data="dataList"
        v-loading="loading"
        :fit="true"
        style="width: 100%"
      >
        <el-table-column
          label="白名单类型"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <el-tag :type="getGiftTypeTagType(row.type)">
              {{ categoryOptions[row.type] || row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="白名单ID" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.content || "-" }}</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="modifyTime"
          label="更新时间"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ formatDate(row.modifyTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="180"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="operatorUserId"
          label="操作人"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column label="备注" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.remark || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageInfo.page"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 礼物表单弹框 -->
    <GiftForm
      v-model="giftFormVisible"
      :gift-data="currentGiftData"
      :is-edit="isEditMode"
      @submit="handleGiftSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useHttp } from "@/hooks/useHttp";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import ImagePreview from "@/components/ImagePreview.vue";
import GiftForm from "./components/GiftForm.vue";

import {
  createWhitelistRecord,
  getWhitelistTypeRecord,
  removeWhitelistRecord,
  WhitelistRecord,
  WhitelistTypeRecord,
} from "@/api/whitelog";

// 白名单类型映射
const WHITELIST_TYPE_MAP = {
  1: "账号封禁",
  2: "设备封禁",
  3: "IP封禁",
};

// 查询参数类型
interface SearchType {
  content: string;
  type?: string;
}

// 多语言名称类型
interface MultiLanguageName {
  zh: string;
  en: string;
  ar: string;
  text?: string;
}

// 礼物信息类型
interface WhiteLogInfo {
  id: string;
  createUser: string | null;
  createTime: string;
  modifyUser: string | null;
  content: string;
  modifyTime: string;
  name: MultiLanguageName;
  type: number;
  operatorUserId: string;
  remark: string;
  enable: boolean;
}

// 查询参数
const searchParams = ref<SearchType>({
  type: null,
  content: "",
});

// 礼物表单相关
const giftFormVisible = ref(false);
const currentGiftData = ref<any>(null);
const isEditMode = ref(false);

// 白名单分类选项
const categoryOptions = ref<WhitelistTypeRecord[]>([]);

// 使用 useHttp hook 管理数据
const {
  dataList,
  loading,
  totals,
  pageInfo,
  loadData,
  handleSizeChange,
  handleCurrentChange,
  resetPagination,
} = useHttp<WhiteLogInfo>("/login-whitelist/page", searchParams, {
  pageKey: "pageIndex",
  pageSizeKey: "pageSize",
  totalKey: "total",
  listKey: "list",
  filterEmptyValues: true, // 过滤空值参数
});

// 查询方法
const handleSearch = () => {
  searchParams.value = {
    ...searchParams.value,
    type: searchParams.value.type == "0" ? null : searchParams.value.type,
  };
  resetPagination();
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
};

// 获取礼物类型标签样式
const getGiftTypeTagType = (giftType: string) => {
  switch (giftType) {
    case "1": // 国家礼物
      return "danger";
    case "2": // 幸运礼物
      return "warning";
    case "3": // 普通礼物
      return "info";
    default:
      return "";
  }
};

// 重置方法
const handleReset = () => {
  searchParams.value = {
    type: null,
    content: "",
  };
  resetPagination();
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 新增方法
const handleAdd = () => {
  isEditMode.value = false;
  currentGiftData.value = null;
  giftFormVisible.value = true;
};

// 编辑方法
const handleEdit = (row: WhiteLogInfo) => {
  isEditMode.value = true;
  currentGiftData.value = { ...row };
  giftFormVisible.value = true;
};

// 删除方法
const handleDelete = async (row: WhiteLogInfo) => {
  try {
    // 显示确认弹窗
    await ElMessageBox.confirm(
      "确定要删除这条记录吗？此操作不可撤销。",
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 用户点击确认后执行删除操作
    const res = await removeWhitelistRecord(row.id);
    ElMessage.success("删除成功");
    loadData();
  } catch (error) {
    // 用户取消操作或发生错误时不执行删除
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      ElMessage.error("删除失败，请重试");
      console.error("删除失败:", error);
    }
  }
};

// 处理礼物表单提交
const handleGiftSubmit = async (formData: any) => {
  try {
    console.log("开始处理表单提交，编辑模式:", isEditMode.value);
    console.log("表单数据:", formData);

    if (isEditMode.value) {
      // 编辑模式 - 使用 GiftUpdateReq
      const updateData: WhitelistRecord = {
        id: currentGiftData.value.id,
        type: formData.type,
        content: formData.content,
        remark: formData.remark || "",
      };
      console.log("编辑数据:", updateData);
      console.log("当前礼物ID:", currentGiftData.value.id);

      // await createWhitelistRecord(currentGiftData.value.id, updateData);
      ElMessage.success("编辑成功");
    } else {
      // 新增模式 - 使用 GiftAddReq
      const addData: WhitelistRecord = {
        type: formData.type,
        content: formData.content,
        remark: formData.remark || "",
      };
      await createWhitelistRecord(addData);
      ElMessage.success("新增成功");
    }

    // 关闭弹框
    giftFormVisible.value = false;

    // 刷新列表
    loadData();
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("操作失败");
  }
};

// 加载封禁分类
const loadCategories = async () => {
  try {
    const response = await getWhitelistTypeRecord();
    categoryOptions.value = {
      ["0"]: "全选" as unknown as WhitelistTypeRecord,
      ...response.data,
    };
  } catch (error) {
    console.error("加载封禁分类失败:", error);
  }
};

// 组件挂载后初始化
onMounted(() => {
  loadData();
  loadCategories();
});
</script>

<style lang="less" scoped>
.gift-list {
  .mb {
    margin-bottom: 15px;

    // 增大查询区域字体
    :deep(.el-form-item__label) {
      font-size: 14px;
      font-weight: 500;
    }

    :deep(.el-input__inner) {
      font-size: 14px;
    }

    :deep(.el-select) {
      font-size: 14px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;

    // 增大分页字体
    :deep(.el-pagination) {
      font-size: 14px;

      .el-pagination__total {
        font-size: 14px;
      }

      .el-pagination__sizes {
        font-size: 14px;
      }

      .el-pagination__jump {
        font-size: 14px;
      }
    }
  }

  .gift-avatar {
    border-radius: 4px;
    transition: transform 0.2s;

    &:hover {
      transform: scale(1.05);
    }
  }

  .coin-price {
    color: #f56c6c;
    font-weight: 500;
  }

  .animation-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60px;
  }

  // 增大表格字体
  :deep(.el-table) {
    font-size: 14px;

    .el-table__header {
      th {
        font-size: 15px;
        font-weight: 600;
        color: #333;
      }
    }

    .el-table__body {
      td {
        font-size: 14px;
        padding: 12px 0;
      }
    }
  }

  // 增大按钮字体
  :deep(.el-button) {
    font-size: 14px;
  }

  // 增大标签字体
  :deep(.el-tag) {
    font-size: 13px;
  }

  // 增大头像尺寸
  :deep(.el-avatar) {
    font-size: 14px;
  }

  .animation-preview {
    width: 60px;
    height: 60px;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
    transition: transform 0.2s;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    gap: 4px;

    &:hover {
      transform: scale(1.05);
      border-color: #409eff;
      background-color: #ecf5ff;
    }

    .el-icon {
      font-size: 18px;
      color: #409eff;
    }

    span {
      font-size: 10px;
      color: #409eff;
      font-weight: 500;
    }
  }

  .no-animation {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    color: #999;
    font-size: 12px;

    .el-icon {
      font-size: 20px;
    }
  }
}

.animation-preview-dialog {
  .animation-preview-content {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .animation-info {
    background-color: #f5f7fa;
    padding: 20px;
    border-radius: 8px;
    border: 1px solid #e4e7ed;

    p {
      margin: 8px 0;
      line-height: 1.6;

      strong {
        color: #333;
      }
    }
  }

  .animation-actions {
    display: flex;
    gap: 10px;
    justify-content: center;
  }
}
</style>
